/*
 * CastDRAndroid
 * Copyright (c) 2014 Christian Holm Christensen
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 *
 */
package org.cholm.media.castdr.fragments;

import android.os.Bundle;

/**
 * Class to store an ID and to save/restore it for app
 *
 * @author cholm
 */
public class IdSaver {
    private final String mTag;
    private Bundle mSavedState = null;
    private int mId = -1;
    private boolean mPreMade = false;

    public IdSaver(String tag) {
        mTag = tag;
    }

    static public String bundle2String(Bundle b) {
        String ret = "{";
        for (String key : b.keySet()) {
            ret += " " + key + " => ";
            Object o = b.get(key);
            if (o instanceof Bundle) {
                ret += bundle2String(b.getBundle(key));
            } else ret += "" + o + " [" + o.getClass().getSimpleName() + "]";
            ret += "\n";
        }
        ret += "}";
        return ret;
    }

    public void restore(Bundle b) {
        // LOGd(mTag, "Restoring from bundle " + bundle2String(b));
        mSavedState = b.getBundle(mTag);
        // LOGd(mTag, "Got back " + bundle2String(mSavedState));
        mId = mSavedState.getInt("ID");
    }

    public Bundle save() {
        mPreMade = true;
        if (mSavedState == null) mSavedState = new Bundle();
        mSavedState.putInt("ID", getId());
        // LOGd(mTag, "Saving to internal state " +
        // bundle2String(mSavedState));
        return mSavedState;
    }

    public Bundle save(Bundle out) {
        if (getId() < 0) {
            out.putBundle(mTag, mSavedState);
        } else {
            out.putBundle(mTag, mPreMade ? mSavedState : save());
        }
        // LOGd(mTag, "Saved state to external bundle " + bundle2String(out));
        mPreMade = false;
        return out;
    }

    public int getId() {
        return mId;
    }

    public void setId(int mId) {
        this.mId = mId;
    }
}
